﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;
using System.Text.RegularExpressions;
using System.IO;

public partial class Manager_Product_AddProduct : System.Web.UI.Page
{
    string Fname;
    protected string sOldName = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["AdminUserID"] == null)
        {
            Response.Write("<script language=javascript>alert('Time is out.');window.open('../Default.aspx','_top');</script>");
            return;
        }
        Ajax.Utility.RegisterTypeForAjax(typeof(Manager_Product_AddProduct));
        if (!IsPostBack)
        {
            BindRate(ddlRate);
            BindRate(ddlRateSaleOf);

            BindTopicList();
            BindCatalogueByTopicID();
            BindData();
            Bindpd_PropertiesDetail(CheckIsNullNoZero(Request.QueryString["CatID"]));
        }
        /* if (ddlKindNo.SelectedValue == "F")
         {
             txtHanBaoHanh.Enabled = false;
             txtDonGia.Enabled = false;
             ddlDonviTinh.SelectedItem.Selected = false;
             ddlDonviTinh.SelectedItem.Text = "Film";
             txtDonGia.Text = "0";
             txtHanBaoHanh.Text = "0";
             txtDonGia.BackColor = System.Drawing.Color.FromName("#eaeaea");
             txtHanBaoHanh.BackColor = System.Drawing.Color.FromName("#eaeaea");
             ddlDonviTinh.Enabled = false;

             ddlOriginalPrice.Enabled = false;
             txtOriginalPrice.BackColor = System.Drawing.Color.FromName("#eaeaea");
             txtOriginalPrice.Text = "0";
             txtOriginalPrice.Enabled = false;
             ddlRate.Enabled = false;
             chkSaleOf.Visible = false;
         }
         else
         {
             ddlDonviTinh.Enabled = true;
             txtHanBaoHanh.Enabled = true;
             txtDonGia.Enabled = true;
         }*/
    }


    private void BindRate(DropDownList ddl)
    {

        ListItem item = new ListItem();
        item.Text = "VNĐ";
        item.Value = "VNĐ";
        item.Selected = true;
        ddl.Items.Add(item);
        item = new ListItem();
        item.Text = "USD";
        item.Value = "USD";
        ddl.Items.Add(item);

    }

    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
    public string AjaxCheckPD(string value, string PDID)
    {
        string flag = "no";
        clsWebShop cls = new clsWebShop();
        DataTable dt = new DataTable();
        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("PDName", value.Trim());
        msg.CreateFirstNode("ExcPDID", PDID);
        dt = cls.Get_ProductByPDNm(msg.GetXmlStr.ToString()).Tables[0];
        if (dt.Rows.Count > 0)
            flag = "yes";
        return flag;
    }
    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
    public DataSet AjaxGetCatByTopicID(string value)
    {
        DataSet ds = null;
        clsWebShop cls = new clsWebShop();
        ds = cls.Get_CatalogueByTopicIDNoneProc(value);
        return ds;
    }



    private void Bindpd_PropertiesDetail(string CatID)
    {
        string PDID = "";
        PccMsg msg = new PccMsg();
        if (Request.QueryString["PDID"] != "" && Request.QueryString["PDID"] != null && ddlTheLoai.SelectedValue == Request.QueryString["CatID"])
        {
            PDID = Request.QueryString["PDID"];
        }


        msg.CreateFirstNode("PDID", PDID);
        msg.CreateFirstNode("PrtID", "0");
        msg.CreateFirstNode("CatID", CatID);

        DataTable dt = new DataTable();
        clsWebShop cls = new clsWebShop();
        dt = cls.Get_pd_PropertyDetailByCondition(msg.GetXmlStr.ToString()).Tables[0];
        if (dt.Rows.Count <= 0)
        {
            msg = new PccMsg();
            msg.CreateFirstNode("PDID", "");
            msg.CreateFirstNode("PrtID", "0");
            msg.CreateFirstNode("CatID", CatID);
            dt = cls.Get_pd_PropertyDetailByCondition(msg.GetXmlStr.ToString()).Tables[0];
        }
        grv_PropertiesDetail.DataSource = dt;
        grv_PropertiesDetail.DataBind();


        if (grv_PropertiesDetail.Rows.Count <= 0)
        {
            lblEmpty.Visible = true;
        }
        else
        {
            lblEmpty.Visible = false;
        }

    }

    private void BindSaleOf(string status)
    {

    }

    private void BindData()
    {
        PccMsg msg = new PccMsg();
        
        if (Request.QueryString["PDID"] != "" && Request.QueryString["PDID"] != null)
        {
            clsWebShop cls = new clsWebShop();
            msg.CreateFirstNode("PdID", Request.QueryString["PDID"]);
            DataTable dt= cls.Get_ProductByProductID(msg.GetXmlStr.ToString()).Tables[0];
            if(dt.Rows.Count>0)
            {
                try
                {
                    clsCommon clsCom = new clsCommon();
                    txtTenSP.Text = dt.Rows[0]["PDName"].ToString();
                    sOldName = dt.Rows[0]["PDName"].ToString();
                    txtDonGia.Text = clsCom.FormatMoney(dt.Rows[0]["Price"].ToString());   

                   
                    try
                    {
                        ddlDonviTinh.SelectedItem.Selected = false;
                        ddlDonviTinh.Items.FindByValue(dt.Rows[0]["Unit"].ToString().Trim()).Selected = true;
                    }
                    catch { }
                    

                    if (dt.Rows[0]["IsHot"].ToString() == "Y")
                        chkHot.Checked = true;


                    txtHanBaoHanh.Text = dt.Rows[0]["Warranty"].ToString();
                    
                    string sURL = dt.Rows[0]["imgURL"].ToString();
                    if (sURL != "" && sURL != null)
                    {
                        imgShowImage.Visible = true;
                        imgShowImage.Style.Add("cursor", "pointer");
                        imgURL.Src = "../../" + sURL;
                        hImg.Value = sURL;
                    }

                    ////////////// 
                    string IsSaleOf = dt.Rows[0]["IsSaleOf"].ToString();
                    if (IsSaleOf == "Y")
                    {
                        chkSaleOf.Checked = true;
                        txtSaleOf.Text = clsCom.FormatMoney(dt.Rows[0]["DiscountPrice"].ToString());
                        try
                        {
                            ddlRateSaleOf.SelectedItem.Selected = false;
                            ddlRateSaleOf.Items.FindByValue(dt.Rows[0]["DiscountRate"].ToString().Trim()).Selected = true;
                            ddlRateSaleOf.Enabled = true;
                        }
                        catch { }
                        txtSaleOf.BackColor = System.Drawing.Color.White; 

                    }
                    else
                    {
                        chkSaleOf.Checked = false;
                        txtSaleOf.Text = clsCom.FormatMoney(dt.Rows[0]["DiscountPrice"].ToString());
                        try
                        {
                            ddlRateSaleOf.SelectedItem.Selected = false;
                            ddlRateSaleOf.Items.FindByValue(dt.Rows[0]["DiscountRate"].ToString().Trim()).Selected = true;
                        }
                        catch { }
                        txtSaleOf.BackColor = System.Drawing.Color.FromName("#eaeaea");
                        txtSaleOf.Attributes.Add("onkeypress", "return false;");            
                        ddlRateSaleOf.Enabled = false;
                    }
                    string Status = dt.Rows[0]["Status"].ToString();
                    if (Status == "C")//Het hang
                    {
                        chkStatus.Checked = true;
                        txtDonGia.Enabled = false;
                        chkSaleOf.Attributes.CssStyle.Add("visibility", "hidden");
                        txtDonGia.BackColor = System.Drawing.Color.FromName("#eaeaea");
                        txtDonGia.Attributes.Add("onkeypress", "return false;");  
                    }
                    else
                    {
                        chkStatus.Checked = false;       
                        txtDonGia.BackColor = System.Drawing.Color.White; 
                    }
                    

                   



                    FCKeditor1.Value = dt.Rows[0]["Descript"].ToString();

                    try
                    {
                        ddlRate.SelectedItem.Selected = false;
                        ddlRate.Items.FindByValue(dt.Rows[0]["Rate"].ToString().Trim()).Selected = true;
                    }
                    catch { }

                    try
                    {
                        if (Request.QueryString["KindNo"] == "F")
                            txtCapacity.Text = dt.Rows[0]["Capacity"].ToString().ToUpper().Replace("GB", "").Trim();
                        else
                        {
                            txtCapacity.Enabled = false;
                            txtCapacity.BackColor = System.Drawing.Color.FromName("#eaeaea");
                        }
                    }
                    catch{}

                }
                catch (Exception ex) { }

            }
        }
    }

    private void BindTopicList()
    {
        clsWebShop cls = new clsWebShop();
        ListItem item = new ListItem();
        ddlChuDe.DataSource = cls.Get_TopicNoneProc().Tables[0];
        ddlChuDe.DataTextField = "TopicName";
        ddlChuDe.DataValueField = "TopicID";
        ddlChuDe.DataBind();
        item.Text = "-- Chọn chủ đề --";
        item.Value = "0";
        ddlChuDe.Items.Insert(0, item);
        ddlChuDe.SelectedItem.Selected = false;

        if (Request.QueryString["TopicID"] != "" && Request.QueryString["TopicID"] != null)
            try
            {
                ddlChuDe.Items.FindByValue(Request.QueryString["TopicID"]).Selected = true;
            }
            catch { }
    }
    /*private void BindStoreList()
    {
        clsWebShop cls = new clsWebShop();
        ListItem item = new ListItem();
        ddlStore.DataSource = cls.Get_StoreByKindNoNoneProc().Tables[0];
        ddlStore.DataTextField = "StName";
        ddlStore.DataValueField = "StID";
        ddlStore.DataBind();
        item.Text = "-- Chọn kho --";
        item.Value = "0";
        ddlStore.Items.Insert(0, item);
        ddlStore.SelectedItem.Selected = false;

        if (Request.QueryString["StID"] != "" && Request.QueryString["StID"] != null)
            ddlStore.Items.FindByValue(Request.QueryString["StID"]).Selected = true;
    }*/

    private void BindCatalogueByTopicID()
    {
        clsWebShop cls = new clsWebShop();

        ListItem item = new ListItem();
        DataTable dt = null;
        dt = cls.Get_CatalogueByTopicIDNoneProc(ddlChuDe.SelectedValue).Tables[0];
        ddlTheLoai.DataSource = dt;
        ddlTheLoai.DataTextField = "Catname";
        ddlTheLoai.DataValueField = "CatID";
        ddlTheLoai.DataBind();
        item.Text = "-- Chọn thể loại--";
        item.Value = "0";
        ddlTheLoai.Items.Insert(0, item);
        try
        {
            if (Request.QueryString["CatID"] != "" && Request.QueryString["CatID"] != null)
                ddlTheLoai.Items.FindByValue(Request.QueryString["CatID"]).Selected = true;
        }
        catch (Exception ex) { }
    }

    private string QueryStringStr(string str)
    {
        return str + "=" + Request.QueryString[str];

    }
    private void ReturnPage()
    {
        Response.Redirect("Product.aspx?KindNo=" + Request.QueryString["KindNo"] + "&CodeID=" + Request.QueryString["CodeID"] + "&" + QueryStringStr("sCatID") + "&" + QueryStringStr("sTopicID") + "&" + QueryStringStr("sPdNm") + "&PageIndex=" + Request.QueryString["PageIndex"]);
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        ReturnPage();
    }
    protected void ddlChuDe_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindCatalogueByTopicID();
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {

        if (FileU_HinhMinhHoa.HasFile)
        {
            Regex objRegex = new Regex(@"(.*?)\.jpg|(.*?)\.png|(.*?)\.gif|(.*?)\.bmp");
            if (!objRegex.IsMatch(FileU_HinhMinhHoa.FileName.ToLower()))
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Chọn file hình ảnh')</script>");
                return;
            }
            else
            {
                FileInfo file = new FileInfo(Server.MapPath("~") + "/Images/Product/" + hImg.Value);
                if (file.Exists)
                    file.Delete();


                string FPath, strdate;
                strdate = System.DateTime.Today.ToString("yyyyMMddhhmmss");
                Fname = "Images/Products/" + strdate + FileU_HinhMinhHoa.FileName;
                FPath = Server.MapPath("~/") + Fname;
                FileU_HinhMinhHoa.SaveAs(FPath);

            }
        }
        else // Giu lai file cu
            Fname = hImg.Value;

        clsWebShop cls = new clsWebShop();
        PccMsg msg = new PccMsg();
        string strProperties = "";
        for (int i = 0; i < grv_PropertiesDetail.Rows.Count; i++)
        {
            Label lblMaTT = (Label)grv_PropertiesDetail.Rows[i].FindControl("lblMaTT");
            TextBox txtTenCTTTSP = (TextBox)grv_PropertiesDetail.Rows[i].FindControl("txtTenCTTTSP");
            if (txtTenCTTTSP.Text != "")
            {
                strProperties += txtTenCTTTSP.Text.Trim() + "|" + lblMaTT.Text.Trim() + "^";
            }

        }


        if (strProperties.Trim() != "")
            strProperties = strProperties.Substring(0, strProperties.LastIndexOf("^"));



        string PDID = "0";
        if (Request.QueryString["PDID"] != "" && Request.QueryString["PDID"] != null)
        {
            PDID = Request.QueryString["PDID"];
        }
        string sBaoHanh = "0";
        if (txtHanBaoHanh.Text != "")
            sBaoHanh = txtHanBaoHanh.Text;

        //Hot
        string hot = "N";
        if (chkHot.Checked == true)
            hot = "Y";
        //SaleOf
        string IsSaleOf = "N";
        if (chkSaleOf.Checked == true)
            IsSaleOf = "Y";
        //Status //C: het hang
        string Status = "N";
        if (chkStatus.Checked == true)
            Status = "C";


        clsCommon clsCom = new clsCommon();

        msg.CreateFirstNode("IsHot", hot);
        msg.CreateFirstNode("PDID", PDID);
        msg.CreateFirstNode("PdName", txtTenSP.Text);
        msg.CreateFirstNode("CatID", ddlTheLoai.Text);
        msg.CreateFirstNode("StID", "");

        msg.CreateFirstNode("Price", txtDonGia.Text.Replace(",", ""));
        msg.CreateFirstNode("Rate", ddlRate.SelectedItem.Text);
        msg.CreateFirstNode("Capacity", txtCapacity.Text+"GB");
        msg.CreateFirstNode("IsSaleOf", IsSaleOf);
        msg.CreateFirstNode("DiscountPrice", clsCom.ConvertToDecimal(txtSaleOf.Text.Replace(",", "")).ToString());
        msg.CreateFirstNode("DiscountRate", ddlRateSaleOf.SelectedItem.Text);
        msg.CreateFirstNode("Status", Status);
        msg.CreateFirstNode("Warranty", sBaoHanh);
        msg.CreateFirstNode("Descript", FCKeditor1.Value.ToString());
        msg.CreateFirstNode("ImgURL", Fname);
        msg.CreateFirstNode("Quantity", "0");
        msg.CreateFirstNode("Unit", ddlDonviTinh.SelectedValue);
        msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
        msg.CreateFirstNode("strProperties", strProperties);

        cls.Ins_Upd_Product(msg.GetXmlStr.ToString());

        txtTenSP.Text = "";
        chkHot.Checked = false;
        txtDonGia.Text = "";
        txtHanBaoHanh.Text = "";
        Bindpd_PropertiesDetail(ddlTheLoai.SelectedValue);
        FCKeditor1.Value = "";
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Success!!!');</script>");

        //       ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Success!!!');window.location.href='AddProduct.aspx'</script>");

        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script> alert('Dữ liệu đã cập nhật thành công');</script>");
        ReturnPage();

    }

    private string CheckIsNull(string value)
    {
        string sReturn = "0";
        if (value != "" && value != null) sReturn = value;
        return sReturn;
    }
    private string CheckIsNullNoZero(string value)
    {
        string sReturn = "-1";
        if (value != "" && value != null) sReturn = value;
        return sReturn;
    }

    protected void ddlChuDe_SelectedIndexChanged1(object sender, EventArgs e)
    {
        BindCatalogueByTopicID();
        Bindpd_PropertiesDetail("-1");
    }
    protected void ddlTheLoai_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlTheLoai.SelectedValue == "0")
        {
            Bindpd_PropertiesDetail("-1");
        }
        else
        {
            Bindpd_PropertiesDetail(ddlTheLoai.SelectedValue);
        }
    }
    protected void grv_PropertiesDetail_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (Request.QueryString["PDID"] != "" && Request.QueryString["PDID"] != null && ddlTheLoai.SelectedValue == Request.QueryString["CatID"])
            {
                TextBox txtTenCTTTSP = (TextBox)e.Row.FindControl("txtTenCTTTSP");
                try
                {
                    txtTenCTTTSP.Text = DataBinder.Eval(e.Row.DataItem, "PrtdDesc").ToString();
                }
                catch { }
            }
        }
    }

}
